import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';

class LocationPage extends StatefulWidget {
  const LocationPage({super.key});

  @override
  State<StatefulWidget> createState() => _LocationPage();
}

class _LocationPage extends State<StatefulWidget> {
  String locationStr = 'GEO座标系：';

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    //增加参数，使用Android的LocationManager定位，避免使用Google服务
    return await Geolocator.getCurrentPosition(
        forceAndroidLocationManager: true);
  }

  Future<void> getCurrentLocation() async {
    try {
      Position position = await _determinePosition();
      print(
          'GEO座标系：Latitude: ${position.latitude}, Longitude: ${position.longitude}');
      setState(() {
        locationStr =
            'GEO座标系：Latitude: ${position.latitude}, Longitude: ${position.longitude}';
      });
    } catch (e) {
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: const Text('定位信息'),
      ),
      body: Center(
        child: Column(children: [
          Text(locationStr),
          FilledButton(
            onPressed: () {
              // 处理按钮点击事件
              getCurrentLocation();
            },
            child: Text('刷新'),
          )
        ]),
      ),
    );
  }
}
